Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
A library to create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.
The form-data npm package is used to create `multipart/form-data` streams that can be used to perform HTTP requests with file uploads and other form data. It is commonly used with request libraries to submit forms and upload files to a server.
Appending fields
This feature allows you to append key-value pairs to the form-data object, which can represent text fields in a form.
const FormData = require('form-data');
const form = new FormData();
form.append('username', 'exampleUser');
form.append('password', 'examplePassword');
Appending files
This feature allows you to append files to the form-data object, which can be used to upload files to a server.
const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();
form.append('file', fs.createReadStream('/path/to/file.txt'), 'file.txt');
Custom headers
This feature allows you to retrieve custom headers required for submitting the form-data object, including the correct `Content-Type` header with the boundary.
const FormData = require('form-data');
const form = new FormData();
const customHeaders = form.getHeaders({'custom-header': 'value'});
// customHeaders can now be used with an HTTP client to send the form with custom headers.
Piping to a HTTP request
This feature demonstrates how to pipe the form-data directly to an HTTP request, which is useful for uploading files and submitting forms.
const FormData = require('form-data');
const http = require('http');
const form = new FormData();
form.append('field', 'value');
const request = http.request({
method: 'post',
host: 'example.com',
path: '/upload',
headers: form.getHeaders()
});
form.pipe(request);
Busboy is a Node.js module for parsing incoming HTML form data. It is particularly good at handling file uploads, but unlike form-data, it is used on the server side to parse incoming requests.
Multiparty is an npm package for parsing `multipart/form-data` requests, similar to busboy. It is also used on the server side and provides an alternative to form-data for handling file uploads and multipart form data.
Multer is a Node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is designed for use with Express and is often preferred for its ease of integration with Express applications, compared to form-data which is more general-purpose.
A library to create readable "multipart/form-data"
streams. Can be used to submit forms and file uploads to other web applications.
The API of this library is inspired by the XMLHttpRequest-2 FormData Interface.
npm install --save form-data
In this example we are constructing a form with 3 fields that contain a string, a buffer and a file stream.
var FormData = require('form-data');
var fs = require('fs');
var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
Also you can use http-response stream:
var FormData = require('form-data');
var http = require('http');
var form = new FormData();
http.request('http://nodejs.org/images/logo.png', function(response) {
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', response);
});
Or @mikeal's request stream:
var FormData = require('form-data');
var request = require('request');
var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', request('http://nodejs.org/images/logo.png'));
In order to submit this form to a web application, call submit(url, [callback])
method:
form.submit('http://example.org/', function(err, res) {
// res – response object (http.IncomingMessage) //
res.resume();
});
For more advanced request manipulations submit()
method returns http.ClientRequest
object, or you can choose from one of the alternative submission methods.
You can provide custom options, such as maxDataSize
:
var FormData = require('form-data');
var form = new FormData({ maxDataSize: 20971520 });
form.append('my_field', 'my value');
form.append('my_buffer', /* something big */);
List of available options could be found in combined-stream
You can use node's http client interface:
var http = require('http');
var request = http.request({
method: 'post',
host: 'example.org',
path: '/upload',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});
Or if you would prefer the 'Content-Length'
header to be set for you:
form.submit('example.org/upload', function(err, res) {
console.log(res.statusCode);
});
To use custom headers and pre-known length in parts:
var CRLF = '\r\n';
var form = new FormData();
var options = {
header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
knownLength: 1
};
form.append('my_buffer', buffer, options);
form.submit('http://example.com/', function(err, res) {
if (err) throw err;
console.log('Done');
});
Form-Data can recognize and fetch all the required information from common types of streams (fs.readStream
, http.response
and mikeal's request
), for some other types of streams you'd need to provide "file"-related information manually:
someModule.stream(function(err, stdout, stderr) {
if (err) throw err;
var form = new FormData();
form.append('file', stdout, {
filename: 'unicycle.jpg', // ... or:
filepath: 'photos/toys/unicycle.jpg',
contentType: 'image/jpeg',
knownLength: 19806
});
form.submit('http://example.com/', function(err, res) {
if (err) throw err;
console.log('Done');
});
});
The filepath
property overrides filename
and may contain a relative path. This is typically used when uploading multiple files from a directory.
For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to form.submit()
as first parameter:
form.submit({
host: 'example.com',
path: '/probably.php?extra=params',
auth: 'username:password'
}, function(err, res) {
console.log(res.statusCode);
});
In case you need to also send custom HTTP headers with the POST request, you can use the headers
key in first parameter of form.submit()
:
form.submit({
host: 'example.com',
path: '/surelynot.php',
headers: {'x-test-header': 'test-header-value'}
}, function(err, res) {
console.log(res.statusCode);
});
Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user.
var form = new FormData();
form.append( 'my_string', 'my value' );
form.append( 'my_integer', 1 );
form.append( 'my_boolean', true );
form.append( 'my_buffer', new Buffer(10) );
form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )
You may provide a string for options, or an object.
// Set filename by providing a string for options
form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );
// provide an object.
form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );
This method adds the correct content-type
header to the provided array of userHeaders
.
Return the boundary of the formData. By default, the boundary consists of 26 -
followed by 24 numbers
for example:
--------------------------515890814546601021194782
Set the boundary string, overriding the default behavior described above.
Note: The boundary must be unique and may not appear in the data.
Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.
var form = new FormData();
form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) );
form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );
axios.post( 'https://example.com/path/to/api',
form.getBuffer(),
form.getHeaders()
)
Note: Because the output is of type Buffer, you can only append types that are accepted by Buffer: string, Buffer, ArrayBuffer, Array, or Array-like Object. A ReadStream for example will result in an error.
Same as getLength
but synchronous.
Note: getLengthSync doesn't calculate streams length.
Returns the Content-Length
async. The callback is used to handle errors and continue once the length has been calculated
this.getLength(function(err, length) {
if (err) {
this._error(err);
return;
}
// add content length
request.setHeader('Content-Length', length);
...
}.bind(this));
Checks if the length of added values is known.
Submit the form to a web application.
var form = new FormData();
form.append( 'my_string', 'Hello World' );
form.submit( 'http://example.com/', function(err, res) {
// res – response object (http.IncomingMessage) //
res.resume();
} );
Returns the form data as a string. Don't use this if you are sending files or buffers, use getBuffer()
instead.
Form submission using request:
var formData = {
my_field: 'my_value',
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
For more details see request readme.
You can also submit a form using node-fetch:
var form = new FormData();
form.append('a', 1);
fetch('http://example.com', { method: 'POST', body: form })
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
In Node.js you can post a file using axios:
const form = new FormData();
const stream = fs.createReadStream(PATH_TO_FILE);
form.append('image', stream);
// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();
axios.post('http://example.com', form, {
headers: {
...formHeaders,
},
})
.then(response => response)
.catch(error => error)
getLengthSync()
method DOESN'T calculate length for streams, use knownLength
options as workaround.2.x
FormData has dropped support for node@0.10.x
.3.x
FormData has dropped support for node@4.x
.Form-Data is released under the MIT license.
FAQs
A library to create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.
The npm package form-data receives a total of 54,566,381 weekly downloads. As such, form-data popularity was classified as popular.
We found that form-data demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.